import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BannerEntity } from '../entities/Banner.entity';
import { ApiOkResponse } from '@nestjs/swagger';
import { ConllectEntity } from '../entities/Conllect.entity';
import { DetailEntity } from '../entities/Detail.entity';
import { ListEntity } from '../entities/List.entity';
import { UserEntity } from '@src/modules/User/User.entity';
@Injectable()//它能够处理构造函数的自动依赖注入
export class FoodService {

    constructor(
        @InjectRepository(ListEntity)
        private readonly listRepository: Repository<ListEntity>,
        @InjectRepository(BannerEntity)
        private readonly bannerRepository: Repository<BannerEntity>,
        @InjectRepository(ConllectEntity)
        private readonly conllectRepository: Repository<ConllectEntity>,
        @InjectRepository(DetailEntity)
        private readonly detailRepository: Repository<DetailEntity>,
        @InjectRepository(UserEntity)
        private readonly userRepository: Repository<UserEntity>

    ) { }

    // 查询数据库中的数据，可以使用 find()、findOne()、findById() 等方法
    // 更新数据库中的数据，可以使用 updateOne()、updateMany()、replaceOne() 等方法
    // 删除数据库中的数据，可以使用 deleteOne()、deleteMany()、remove() 等方法

    //轮播图
    async findAll(): Promise<BannerEntity[]> {
        const banner = await this.bannerRepository.find();
        return banner;
    }

    //主页美食列表
    async findAllList(): Promise<ListEntity[]> {
        return await this.listRepository.find();
    }

    //用户收藏列表

    async findAllConllect(userId: any): Promise<ConllectEntity[]> {
        return this.conllectRepository.find({
            where: { user: { id: userId } },
            relations: ["user"]
        })
    }


    //根据美食id查询美食详情页
    async findDetail(foodsid: any): Promise<DetailEntity[]> {
        return await this.detailRepository.find({
            where: { id: foodsid }
        })
    }



    //搜索
    async searchFoods(query: any): Promise<ListEntity[]> {
        console.log('Received query:', query); // 打印调试信息
        return await this.listRepository
            .createQueryBuilder('foods')
            .where('foods.foods_title LIKE :query', { query: `%${query}%` })
            .getMany();
    }


    //收藏删除
    async deleteCollect(userId: string, collectId: string): Promise<any> {
        const detalecollect = await this.conllectRepository.delete({ id: collectId, user: { id: userId } });
        return detalecollect;
    }

    // 增加收藏
    async addCollect(userId: string, collectData: Partial<ConllectEntity>): Promise<ConllectEntity> {
        const user = await this.userRepository.findOne({ where: { id: userId } });
        if (!user) {
            throw new Error('User not found');
        }
        const collect = this.conllectRepository.create({ ...collectData, user });
        return this.conllectRepository.save(collect);
    }
}